package com.zhongen.oa.service.impl;

import com.zhongen.oa.service.AppletService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class AppletServiceImpl implements AppletService {

	private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";

	public static void sendSubscribeMessage(String accessToken, String openid, String templateId, String page,
			String data) {
		try {
			String url = API_URL + "?access_token=" + accessToken;

			URL apiUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.setDoOutput(true);

			// 构建请求体
			String body = buildRequestBody(openid, templateId, page, data);
			byte[] requestBodyBytes = body.getBytes(StandardCharsets.UTF_8);

			// 发送请求
			connection.getOutputStream().write(requestBodyBytes);

			// 读取响应
			int responseCode = connection.getResponseCode();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder response = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				response.append(line);
			}
			reader.close();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 请求成功处理逻辑
				System.out.println("发送订阅消息成功");
				System.out.println(response.toString());
			}
			else {
				// 请求失败处理逻辑
				System.out.println("发送订阅消息失败");
				System.out.println("响应码：" + responseCode);
				System.out.println(response.toString());
			}

			connection.disconnect();
		}
		catch (IOException e) {
			// 异常处理逻辑
			e.printStackTrace();
		}
	}

	private static String buildRequestBody(String openid, String templateId, String page, String data) {
		// 构建请求体的JSON字符串
		return String.format("{\"touser\":\"%s\",\"template_id\":\"%s\",\"page\":\"%s\",\"data\":%s}", openid,
				templateId, page, data);
	}

}
